<template>
  <div class="search-suggestion">
    <van-cell icon="search" v-for="(item, index) in suggestions" :key="index">
      <span
        slot="title"
        v-html="highlight(item)"
        @click="$emit('search', item)"
      ></span>
    </van-cell>
  </div>
</template>

<script>
// lodash 支持按需加载，有利于打包结果优化
import { debounce } from 'lodash'
import { getSearchSuggestion } from '@/api/search.js'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      suggestions: []
    }
  },
  computed: {},
  watch: {
    //   监听父组件传递的数据
    searchText: {
      handler: debounce(function (val) {
        this.loadSearchSuggestion(val)
      }, 1500),
      //   handler (val) {
      //     console.log(val)
      //     this.loadSearchSuggestion(val)
      //   },
      //   进入就触发
      immediate: true
    }
  },
  created () {},
  mounted () {},
  methods: {
    async loadSearchSuggestion (q) {
      try {
        const { data } = await getSearchSuggestion(q)
        // console.log(data)
        this.suggestions = data.data.options
        console.log(this.suggestions, 999)
      } catch (err) {
        this.$toast('获取失败')
      }
    },
    // 字体高亮
    highlight (text) {
      if (text === null) return
      const highlightStr = `<span class="active">${this.searchText}</span>`
      // 正则表达式 // 中间的内容都会当作匹配字符来使用，而不是数据变量
      // 如果需要根据数据变量动态的创建正则表达式，则手动 new RegExp
      // RegExp 正则表达式构造函数
      //    参数1：匹配模式字符串，它会根据这个字符串创建正则对象
      //    参数2：匹配模式，要写到字符串中
      const reg = new RegExp(this.searchText, 'gi')
      // text.replace(/匹配的内容/gi, highlightStr)
      return text.replace(reg, highlightStr)
    }
  }
}
</script>

<style scoped lang="less">
.search-suggestion {
  /deep/ span.active {
    color: #3296fa;
  }
}
</style>
